<template>
  <view class="home-container">
    <!-- 横幅区域（中英文都显示） -->
    <view class="banner-container">
      <!-- 横幅轮播 -->
      <swiper
        v-if="banners.length > 0"
        class="banner-swiper"
        :indicator-dots="banners.length > 1"
        :autoplay="banners.length > 1"
        :interval="5000"
        :duration="500"
        indicator-color="rgba(255, 255, 255, 0.5)"
        indicator-active-color="#fff"
        @change="onBannerChange"
      >
        <swiper-item v-for="banner in banners" :key="banner.id" class="banner-item">
          <view class="banner-content">
            <!-- 暂时隐藏图片，只显示文字内容 -->
            <!-- <image
              :src="banner.imageUrl"
              class="banner-image"
              mode="aspectFill"
              :lazy-load="true"
              @error="onBannerImageError"
            /> -->
            <view class="banner-text-only">
              <text class="banner-text">{{ banner.title }}{{ banner.description ? '：' + banner.description : '' }}</text>
              <view class="banner-close" @click.stop="closeBanner(banner.id)">
                <uni-icons type="close" size="14" color="#fff"></uni-icons>
              </view>
            </view>
          </view>
        </swiper-item>
      </swiper>

      <!-- 加载状态 -->
      <view v-if="bannersLoading" class="banner-loading">
        <uni-icons type="spinner-cycle" size="20" color="#999"></uni-icons>
        <text class="loading-text">加载中...</text>
      </view>

      <!-- 错误状态 -->
      <view v-if="bannersError && !bannersLoading" class="banner-error" @click="loadBanners">
        <uni-icons type="refreshempty" size="20" color="#999"></uni-icons>
        <text class="error-text">{{ bannersError }}，点击重试</text>
      </view>
    </view>

    <!-- 搜索框 -->
    <view class="search-bar">
      <view class="catalog-button" @click="openCatalogDrawer">
        <view class="button-icon">
          <uni-icons type="list" size="18" color="#fff"></uni-icons>
        </view>
        <text class="button-text">目录</text>
      </view>
      <input
        class="search-input"
        type="text"
        :placeholder="currentLanguage === 'en' ? '搜索书名或作者' : '搜索绘本，如\'唐诗\'、\'故事\''"
        v-model="searchKeyword"
        @input="onSearchInput"
      />
      <view class="search-icon" @click="performSearch">
        <uni-icons type="search" size="20"></uni-icons>
      </view>
      <view class="audio-button" @click="goToAudio">
        <view class="button-icon">
          <uni-icons type="sound" size="18" color="#fff"></uni-icons>
        </view>
        <text class="button-text">磨耳朵</text>
      </view>
    </view>

    <!-- 功能目录与绘本集展示区 -->
    <view class="category-section">
      <!-- 分类标题栏 -->
      <view class="category-header">
        <text class="category-title">{{ currentLanguage === 'en' ? '英文绘本集' : '中文绘本集' }}</text>
        <view class="language-switch" @click="switchLanguage">
          <wd-icon name="translate-bold" size="16px" color="#666"></wd-icon>
          <text class="switch-text">{{ currentLanguage === 'en' ? '中文' : 'English' }}</text>
        </view>
      </view>

      <!-- 分类标签 -->
      <view class="category-tabs">
        <view
          v-for="item in categories"
          :key="item.name"
          class="category-item"
          :class="{ active: currentCategory === item.name }"
          @click="switchCategory(item.name)"
        >
          <view class="category-icon-wrapper">
            <text class="iconfont" :class="item.icon"></text>
          </view>
          <text>{{ item.name }}</text>
        </view>
      </view>
    </view>

    <!-- 绘本集展示区 -->
    <view v-if="showBookSets" class="book-section">
      <view class="section-header">
        <text class="section-title">{{ currentCategory }}绘本集</text>
        <view class="section-actions">
          <text class="section-more" @click="viewMoreBookSets">更多 &gt;</text>
          <view class="clear-button" @click="toggleBookSetsCollapse">
            <uni-icons
              :type="isBookSetsCollapsed ? 'arrow-down' : 'arrow-up'"
              size="16"
              color="#fff"
            ></uni-icons>
          </view>
        </view>
      </view>

      <view v-if="!isBookSetsCollapsed">
        <!-- 加载状态 -->
        <view v-if="bookSetsLoading" class="loading-container">
          <uni-icons type="spinner-cycle" size="24" color="#42BBFF"></uni-icons>
          <text class="loading-text">加载中...</text>
        </view>

        <!-- 绘本集网格 -->
        <view v-else-if="displayBookSets.length > 0" class="book-grid">
          <view
            v-for="(bookSet, index) in displayBookSets"
            :key="bookSet.id"
            class="book-grid-item"
            @click="openBookSetDetail(bookSet)"
          >
            <view class="book-cover-container">
              <image class="book-cover-grid" :src="bookSet.cover" mode="aspectFill" />
              <view class="book-count-badge">{{ bookSet.bookCount }}本</view>
            </view>
            <text class="book-title-grid">{{ bookSet.title }}</text>
            <text class="book-source-grid">{{ bookSet.categoryName || (bookSet as any).source }}</text>
          </view>
        </view>

        <!-- 空状态 -->
        <view v-else class="empty-container">
          <text class="empty-text">暂无{{ currentCategory }}绘本集</text>
        </view>
      </view>
    </view>

    <!-- 阅读计划（仅英文模式显示） -->
    <view v-if="currentLanguage === 'en'" class="plan-section">
      <view class="section-header">
        <text class="section-title">我的阅读计划</text>
        <text class="section-more" @click="createPlan">+ 创建计划</text>
      </view>

      <!-- 加载状态 -->
      <view v-if="plansLoading" class="plan-loading">
        <uni-icons type="spinner-cycle" size="24" color="#42BBFF"></uni-icons>
        <text class="loading-text">加载中...</text>
      </view>

      <!-- 计划列表 -->
      <swiper
        v-else-if="readingPlans.length > 0"
        class="plan-swiper"
        :indicator-dots="readingPlans.length > 1"
        :autoplay="false"
        :current="currentPlanIndex"
        @change="onPlanChange"
      >
        <swiper-item v-for="plan in readingPlans" :key="plan.id">
          <view class="plan-card" @click="openPlanDetail(plan)">
            <view class="plan-content">
              <!-- 左侧绘本集封面 -->
              <view class="plan-cover-section">
                <image class="plan-cover" :src="(plan as any).cover || plan.bookSets?.[0]?.cover || 'https://img3.doubanio.com/view/subject/s/public/s2768378.jpg'" mode="aspectFill" />
              </view>

              <!-- 右侧计划信息 -->
              <view class="plan-info">
                <view class="plan-title-row">
                  <text class="plan-name">{{ plan.planName }}</text>
                  <view class="plan-status" :class="getPlanStatusClass(plan.status)">
                    <text class="status-text">{{ getPlanStatusText(plan.status) }}</text>
                  </view>
                </view>
                <view class="plan-progress">
                  <view class="progress-bar">
                    <view
                      class="progress-fill"
                      :style="{ width: (plan.completedBooks / plan.totalBooks * 100) + '%' }"
                    ></view>
                  </view>
                  <text class="progress-text">{{ plan.completedBooks }}/{{ plan.totalBooks }}本</text>
                </view>
                <view class="plan-days">
                  <text class="current-day">第{{ plan.currentDay }}/</text>
                  <text class="total-days"> {{ plan.estimatedDays }}天</text>
                </view>
              </view>
            </view>
          </view>
        </swiper-item>
      </swiper>

      <!-- 空状态 -->
      <view v-else class="plan-empty">
        <uni-icons type="calendar" size="48" color="#ccc"></uni-icons>
        <text class="empty-text">暂无计划</text>
        <text class="empty-desc">点击右上角创建您的第一个阅读计划</text>
      </view>
    </view>

    <!-- 最近阅读的绘本集 -->
    <view class="book-section" v-if="!recentReadingLoading && recentlyRead.length > 0">
      <view class="section-header">
        <text class="section-title">最近阅读</text>
        <view class="section-actions">
          <text class="section-more" @click="goToReadingHistory">更多历史 &gt;</text>
          <view class="clear-button" @click="clearRecentBooks">
            <uni-icons type="trash" size="16" color="#fff"></uni-icons>
          </view>
        </view>
      </view>
      <view class="book-grid">
        <view v-for="book in recentlyRead" :key="book.bookSetId || (book as any).id" class="book-grid-item" @click="openPictureBookSet(book)">
          <view class="book-cover-container">
            <image class="book-cover-grid" :src="book.cover || (book as any).bookCoverUrl" mode="aspectFill" />
            <view class="book-count-badge">{{ book.bookCount || '1' }}本</view>
          </view>
          <text class="book-title-grid">{{ book.bookSetTitle || (book as any).title }}</text>
          <text class="book-source-grid">{{ book.source || '最近阅读' }}</text>
        </view>
      </view>
    </view>

    <!-- 最近阅读加载状态 -->
    <view v-if="recentReadingLoading" class="book-section">
      <view class="section-header">
        <text class="section-title">最近阅读</text>
      </view>
      <view class="loading-container">
        <uni-icons type="spinner-cycle" size="24" color="#42BBFF"></uni-icons>
        <text class="loading-text">加载中...</text>
      </view>
    </view>

    <!-- 小猪佩奇专区/古诗词专区 -->
    <view class="book-section">
      <view class="section-header">
        <text class="section-title">{{ currentLanguage === 'en' ? '小猪佩奇' : '古诗词' }}</text>
      </view>

      <!-- 加载状态 -->
      <view v-if="peppaLoading" class="loading-container">
        <uni-icons type="spinner-cycle" size="24" color="#42BBFF"></uni-icons>
        <text class="loading-text">加载中...</text>
      </view>

      <!-- 绘本集列表 -->
      <view v-else class="book-grid">
        <view v-for="book in peppaBookSets" :key="book.id" class="book-grid-item" @click="openPictureBookSet(book)">
          <view class="book-cover-container">
            <image class="book-cover-grid" :src="book.cover" mode="aspectFill" />
            <view class="book-count-badge">{{ book.bookCount }}本</view>
          </view>
          <text class="book-title-grid">{{ book.title }}</text>
          <text class="book-source-grid">{{ book.source || book.categoryName }}</text>
        </view>
      </view>
    </view>

    <!-- 推荐绘本集 -->
    <view class="book-section">
      <view class="section-header">
        <text class="section-title">{{ currentLanguage === 'en' ? '为你推荐' : '推荐合集' }}</text>
      </view>
      <view class="book-grid">
        <view v-for="book in recommendedBookSets" :key="book.id" class="book-grid-item" @click="openPictureBookSet(book)">
          <view class="book-cover-container">
            <image class="book-cover-grid" :src="book.cover" mode="aspectFill" />
            <view class="book-count-badge">{{ book.bookCount }}本</view>
          </view>
          <text class="book-title-grid">{{ book.title }}</text>
          <text class="book-source-grid">{{ book.categoryName || (book as any).source }}</text>
        </view>
      </view>
    </view>

    <!-- 目录抽屉面板 -->
    <view v-if="showCatalogDrawer" class="catalog-drawer-overlay" @click="closeCatalogDrawer">
      <view class="catalog-drawer" @click.stop>
        <view class="drawer-header">
          <text class="drawer-title">{{ currentLanguage === 'en' ? '英文书架' : '中文书架' }}</text>
          <view class="drawer-close" @click="closeCatalogDrawer">
            <uni-icons type="close" size="20" color="#666"></uni-icons>
          </view>
        </view>
        <scroll-view class="drawer-content" scroll-y>
          <view
            v-for="category in categories"
            :key="category.id"
            class="drawer-item"
            :class="{ active: currentCategory === category.name }"
            @click="selectCategoryFromDrawer(category.name)"
          >
            <view class="drawer-item-content">
              <view class="drawer-item-icon">
                <text class="iconfont" :class="category.icon"></text>
              </view>
              <text class="drawer-item-text">{{ category.name }}</text>
            </view>
            <view v-if="currentCategory === category.name" class="drawer-item-check">
              <uni-icons type="checkmarkempty" size="16" color="#007AFF"></uni-icons>
            </view>
          </view>
        </scroll-view>
      </view>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue'
import { onLoad, onShow, onUnload } from '@dcloudio/uni-app'
import { getRecommendedBookSets, searchBookSets } from '@/api'
import { getRecentReading, clearRecentReading } from '@/api/record'
import { getReadingPlanList } from '@/api/plan'
import { getActiveBanners } from '@/api/banner'
import { useUserStore } from '@/store/user'
import type { CategoryRespVO, BookSetRespVO } from '@/api'
import type { RecentReadingRespVO } from '@/api/types/record'
import type { ReadingPlanRespVO } from '@/api/types/plan'
import type { BannerRespVO } from '@/api/types/banner'

// 用户store
const userStore = useUserStore()

// 横幅数据
const banners = ref<BannerRespVO[]>([])
const bannersLoading = ref(false)
const bannersError = ref('')
const currentBannerIndex = ref(0)

// 搜索相关
const searchKeyword = ref('')

// 语言切换相关
const currentLanguage = ref<'en' | 'zh'>('en') // 默认英文

// 分类相关
const currentCategory = ref('全部')
// 英文分类数据
const englishCategories = ref<CategoryRespVO[]>([
  { id: 1, name: '全部', description: '所有英文绘本分类', sortOrder: 0, status: 1, language: 'en', createTime: '', updateTime: '', icon: 'icon-qiehuankapian' },
  { id: 2, name: '分级阅读', description: '按难度分级的英文阅读绘本', sortOrder: 1, status: 1, language: 'en', createTime: '', updateTime: '', icon: 'icon-shili' },
  { id: 3, name: '桥梁书', description: '从绘本过渡到章节书的桥梁读物', sortOrder: 2, status: 1, language: 'en', createTime: '', updateTime: '', icon: 'icon-xunlianrenwu' },
  { id: 4, name: '章节书', description: '适合独立阅读的英文章节书', sortOrder: 3, status: 1, language: 'en', createTime: '', updateTime: '', icon: 'icon-shiyongshouce' },
  { id: 5, name: '其它', description: '其他类型的英文绘本', sortOrder: 4, status: 1, language: 'en', createTime: '', updateTime: '', icon: 'icon-gengduo' }
])

// 中文分类数据
const chineseCategories = ref<CategoryRespVO[]>([
  { id: 11, name: '全部', description: '所有中文绘本分类', sortOrder: 0, status: 1, language: 'zh', createTime: '', updateTime: '', icon: 'icon-qiehuankapian' },
  { id: 12, name: '古诗词', description: '中华古典诗词绘本', sortOrder: 1, status: 1, language: 'zh', createTime: '', updateTime: '', icon: 'icon-shili' },
  { id: 13, name: '成语故事', description: '成语典故和寓意故事', sortOrder: 2, status: 1, language: 'zh', createTime: '', updateTime: '', icon: 'icon-xunlianrenwu' },
  { id: 14, name: '寓言故事', description: '经典寓言和哲理故事', sortOrder: 3, status: 1, language: 'zh', createTime: '', updateTime: '', icon: 'icon-shiyongshouce' },
  { id: 15, name: '传统文化', description: '中华传统文化绘本', sortOrder: 4, status: 1, language: 'zh', createTime: '', updateTime: '', icon: 'icon-gengduo' }
])

// 当前分类数据（根据语言动态切换）
const categories = computed(() => {
  return currentLanguage.value === 'en' ? englishCategories.value : chineseCategories.value
})

// 加载状态
const bookSetsLoading = ref(false)
const recentReadingLoading = ref(false)
const peppaLoading = ref(false)

// 目录抽屉
const showCatalogDrawer = ref(false)

// 绘本集展示区相关
const showBookSets = ref(false)
const isBookSetsCollapsed = ref(false)
const categoryBookSets = ref<BookSetRespVO[]>([])
const displayBookSets = ref<BookSetRespVO[]>([])

// 推荐绘本集数据
const recommendedBookSets = ref<BookSetRespVO[]>([])

// 最近阅读数据
const recentlyRead = ref<RecentReadingRespVO[]>([])



// 阅读计划数据
const readingPlans = ref<ReadingPlanRespVO[]>([])
const plansLoading = ref(false)

// 当前显示的计划索引
const currentPlanIndex = ref(0)



// 小猪佩奇专区数据
const peppaBookSets = ref<BookSetRespVO[]>([])

// 计划切换事件
function onPlanChange(event: any) {
  currentPlanIndex.value = event.detail.current
}

// 跳转到阅读计划详情页面
function openPlanDetail(plan: any) {
  uni.navigateTo({
    url: `/pages-sub/plan/plan-detail/index?planId=${plan.id}&planName=${encodeURIComponent(plan.planName)}`
  })
}

// 创建计划
function createPlan() {
  uni.navigateTo({
    url: '/pages-sub/plan/create-plan/index'
  })
}

// 获取计划状态文本
function getPlanStatusText(status: string) {
  const statusMap: Record<string, string> = {
    'active': '进行中',
    'paused': '已暂停',
    'completed': '已完成',
    'cancelled': '已取消'
  }
  return statusMap[status] || '进行中'
}

// 获取计划状态样式类
function getPlanStatusClass(status: string) {
  return {
    'status-active': status === 'active',
    'status-paused': status === 'paused',
    'status-completed': status === 'completed',
    'status-cancelled': status === 'cancelled'
  }
}

// 横幅相关方法
async function loadBanners() {
  try {
    bannersLoading.value = true
    bannersError.value = ''

    const response = await getActiveBanners({ limit: 5 })
    if (response.code === 0 && response.data) {
      banners.value = response.data
    } else {
      console.warn('横幅API调用失败:', response.msg)
      banners.value = []
    }
  } catch (error) {
    console.error('加载横幅失败:', error)
    banners.value = []
  } finally {
    bannersLoading.value = false
  }
}

// 横幅轮播切换
function onBannerChange(event: any) {
  currentBannerIndex.value = event.detail.current
}

// 关闭横幅
function closeBanner(bannerId: number) {
  // 从横幅列表中移除指定的横幅
  banners.value = banners.value.filter(banner => banner.id !== bannerId)

  // 如果没有横幅了，重置当前索引
  if (banners.value.length === 0) {
    currentBannerIndex.value = 0
  } else if (currentBannerIndex.value >= banners.value.length) {
    currentBannerIndex.value = banners.value.length - 1
  }
}





// 搜索输入处理
function onSearchInput() {
  // 实时搜索逻辑
}

// 执行搜索
function performSearch() {
  if (!searchKeyword.value.trim()) {
    uni.showToast({
      title: '请输入搜索关键词',
      icon: 'none'
    })
    return
  }

  // 跳转到分类页面进行搜索
  const language = currentLanguage.value === 'en' ? 'english' : 'chinese'
  uni.navigateTo({
    url: `/pages/category/index?keyword=${encodeURIComponent(searchKeyword.value)}&language=${language}`
  })
}

// 跳转到磨耳朵功能
function goToAudio() {
  uni.navigateTo({
    url: '/pages/audio/index'
  })
}

// 语言切换功能
function switchLanguage() {
  // 切换语言
  currentLanguage.value = currentLanguage.value === 'en' ? 'zh' : 'en'

  // 保存到本地缓存
  uni.setStorageSync('bookshelf_language', currentLanguage.value)

  // 重置分类选择
  currentCategory.value = '全部'

  // 清空搜索关键词
  searchKeyword.value = ''

  // 重新加载数据
  loadDataByLanguage()
}

// 根据语言加载数据
async function loadDataByLanguage() {
  if (currentLanguage.value === 'en') {
    // 英文模式：加载推荐绘本集、最近阅读、阅读计划、小猪佩奇专区（不重新加载横幅）
    await Promise.all([
      loadRecommendedBookSets(),
      loadRecentReading(),
      loadReadingPlans(),
      loadPeppaBookSets()
    ])
  } else {
    // 中文模式：加载最近阅读、推荐绘本集、古诗词专区（不重新加载横幅）
    await Promise.all([
      loadRecentReading(),
      loadRecommendedBookSets(),
      loadPoetryBookSets()
    ])
  }

  // 如果当前有显示分类绘本集，需要重新加载当前分类的数据
  if (showBookSets.value) {
    loadCategoryBookSets(currentCategory.value)
  }
}

// 切换分类
function switchCategory(categoryName: string) {
  currentCategory.value = categoryName

  // 显示绘本集展示区
  showBookSets.value = true
  isBookSetsCollapsed.value = false

  // 加载对应分类的绘本集
  loadCategoryBookSets(categoryName)
}

// 加载分类绘本集
async function loadCategoryBookSets(categoryName: string) {
  try {
    bookSetsLoading.value = true

    // 查找分类ID
    const category = categories.value.find(cat => cat.name === categoryName)
    const categoryId = category?.id

    // 调用API获取绘本集
    const params = {
      pageNo: 1,
      pageSize: 12,
      lang: currentLanguage.value,
      ...(categoryId && categoryId > (currentLanguage.value === 'en' ? 1 : 11) ? { categoryId } : {}) // 排除"全部"分类
    }

    const response = await getRecommendedBookSets(params)
    if (response && response.code === 0) {
      // 后端直接返回数组，不是 { list: [...] } 格式
      const sets = response.data || []
      categoryBookSets.value = sets
      // 显示前9个（3行3列）
      displayBookSets.value = sets.slice(0, 9)
    } else {
      console.warn('分类绘本集API响应格式异常:', response)
      categoryBookSets.value = []
      displayBookSets.value = []
    }
  } catch (error) {
    console.error('加载分类绘本集失败:', error)
    categoryBookSets.value = []
    displayBookSets.value = []
  } finally {
    bookSetsLoading.value = false
  }
}

// 切换绘本集展示区折叠状态
function toggleBookSetsCollapse() {
  isBookSetsCollapsed.value = !isBookSetsCollapsed.value
}

// 查看更多绘本集
function viewMoreBookSets() {
  const language = currentLanguage.value === 'en' ? 'english' : 'chinese'
  uni.navigateTo({
    url: `/pages/category/index?category=${encodeURIComponent(currentCategory.value)}&language=${language}`
  })
}

// 打开绘本集详情
function openBookSetDetail(bookSet: any) {
  const setId = bookSet.id || bookSet.bookSetId
  uni.navigateTo({
    url: `/pages-sub/reading/picture-book-set/index?setId=${setId}`
  })
}

// 打开绘本集（兼容不同数据格式）
function openPictureBookSet(item: any) {
  const setId = item.id || item.bookSetId || item.bookId
  if (setId) {
    uni.navigateTo({
      url: `/pages-sub/reading/picture-book-set/index?setId=${setId}`
    })
  }
}

// 打开目录抽屉
function openCatalogDrawer() {
  showCatalogDrawer.value = true
}

// 关闭目录抽屉
function closeCatalogDrawer() {
  showCatalogDrawer.value = false
}

// 从抽屉选择分类
function selectCategoryFromDrawer(categoryName: string) {
  showCatalogDrawer.value = false
  // 调用switchCategory函数来触发分类切换逻辑
  switchCategory(categoryName)
}

// 跳转到阅读记录页面
function goToReadingHistory() {
  uni.navigateTo({
    url: '/pages-sub/profile/reading-history/index'
  })
}

// 清空最近阅读
function clearRecentBooks() {
  uni.showModal({
    title: '确认清空',
    content: '确定清空最近阅读记录吗？',
    success: async (res) => {
      if (res.confirm) {
        try {
          uni.showLoading({ title: '清空中...' })

          const language = currentLanguage.value === 'en' ? 'en' : 'zh'
          const response = await clearRecentReading(language)
          if (response && response.code === 0) {
            recentlyRead.value = []
            uni.showToast({
              title: '已清空',
              icon: 'success'
            })
          } else {
            throw new Error('清空失败')
          }
        } catch (error) {
          console.error('清空最近阅读失败:', error)
          uni.showToast({
            title: '清空失败，请重试',
            icon: 'none'
          })
        } finally {
          uni.hideLoading()
        }
      }
    }
  })
}




// API调用函数

async function loadRecommendedBookSets() {
  try {
    bookSetsLoading.value = true
    const response = await getRecommendedBookSets({ pageNo: 1, pageSize: 12, lang: currentLanguage.value })

    // 检查响应是否有效
    if (response && response.code === 0) {
      // 后端直接返回数组，不是 { list: [...] } 格式
      recommendedBookSets.value = response.data || []
    } else {
      console.warn('推荐绘本集API响应格式异常:', response)
      throw new Error('API响应格式异常')
    }
  } catch (error) {
    console.error('加载推荐绘本集失败:', error)
    recommendedBookSets.value = []
  } finally {
    bookSetsLoading.value = false
  }
}

async function loadRecentReading() {
  try {
    recentReadingLoading.value = true
    const language = currentLanguage.value === 'en' ? 'en' : 'zh'
    const response = await getRecentReading({ language, limit: 3 })

    // 检查响应是否有效
    if (response && response.code === 0) {
      recentlyRead.value = response.data || []
    } else if (response && response.code === 401) {
      // 401错误已经在请求拦截器中处理，这里不需要额外处理
      return
    } else {
      console.warn('最近阅读API响应格式异常:', response)
      recentlyRead.value = []
    }
  } catch (error: any) {
    console.error('加载最近阅读失败:', error)

    // 检查是否是401错误（已经在拦截器中处理）
    if (error?.data?.code === 401) {
      return
    }

    // 其他错误处理
    recentlyRead.value = []
    uni.showToast({
      title: '加载最近阅读失败',
      icon: 'none',
      duration: 2000
    })
  } finally {
    recentReadingLoading.value = false
  }
}

// 加载阅读计划
async function loadReadingPlans() {
  try {
    plansLoading.value = true
    const response = await getReadingPlanList('active')

    if (response && response.code === 0) {
      readingPlans.value = response.data || []
    } else {
      console.warn('阅读计划API响应格式异常:', response)
      throw new Error('API响应格式异常')
    }
  } catch (error) {
    console.error('加载阅读计划失败:', error)
    // API失败时显示空状态，不使用备用数据
    readingPlans.value = []
    uni.showToast({
      title: '加载计划失败',
      icon: 'none',
      duration: 2000
    })
  } finally {
    plansLoading.value = false
  }
}

// 加载小猪佩奇专区绘本集
async function loadPeppaBookSets() {
  try {
    peppaLoading.value = true

    // 使用搜索API获取小猪佩奇相关绘本集
    const response = await searchBookSets({
      keyword: '小猪佩奇',
      language: 'english', // 小猪佩奇是英文绘本
      pageNo: 1,
      pageSize: 10
    })

    if (response && response.code === 0) {
      const sets = response.data?.list || []
      peppaBookSets.value = sets
    } else {
      console.warn('小猪佩奇绘本集API响应格式异常:', response)
      throw new Error('API响应格式异常')
    }
  } finally {
    peppaLoading.value = false
  }
}

// 加载古诗词绘本集（中文模式专用）
async function loadPoetryBookSets() {
  try {
    peppaLoading.value = true // 复用peppaLoading状态

    // 查找古诗词分类ID
    const poetryCategory = chineseCategories.value.find(cat => cat.name === '古诗词')
    const categoryId = poetryCategory?.id

    const params = {
      pageNo: 1,
      pageSize: 6, // 显示6个古诗词绘本集
      lang: 'zh',
      ...(categoryId ? { categoryId } : {})
    }

    const response = await getRecommendedBookSets(params)
    if (response && response.code === 0) {
      peppaBookSets.value = response.data || [] // 复用peppaBookSets数据
    } else {
      console.warn('古诗词绘本集API响应格式异常:', response)
      peppaBookSets.value = []
    }
  } catch (error) {
    console.error('加载古诗词绘本集失败:', error)
    peppaBookSets.value = []
  } finally {
    peppaLoading.value = false
  }
}

onLoad(() => {
  // 首先检查用户登录状态
  const isLoggedIn = userStore.isLoggedIn

  // 如果用户未登录，直接跳转到登录页面
  if (!isLoggedIn) {
    uni.reLaunch({
      url: '/pages/login/index?redirect=' + encodeURIComponent('/pages/index/index')
    })
    return
  }

  // 读取本地缓存的语言设置
  const cachedLanguage = uni.getStorageSync('bookshelf_language')
  if (cachedLanguage && (cachedLanguage === 'en' || cachedLanguage === 'zh')) {
    currentLanguage.value = cachedLanguage
  }

  // 用户已登录，加载横幅数据（只加载一次）
  loadBanners()

  // 根据语言加载其他页面数据
  loadDataByLanguage()

  // 监听计划变更事件
  uni.$on('planChanged', () => {
    console.log('收到计划变更事件，重新加载计划数据')
    if (currentLanguage.value === 'en') {
      loadReadingPlans()
    }
  })
})

onShow(() => {
  // 页面显示时也检查登录状态
  const isLoggedIn = userStore.isLoggedIn
  if (!isLoggedIn) {
    uni.reLaunch({
      url: '/pages/login/index?redirect=' + encodeURIComponent('/pages/index/index')
    })
    return
  }

  // 重新加载计划数据，确保显示最新的进度信息（仅英文模式）
  if (currentLanguage.value === 'en') {
    console.log('书架页面onShow - 重新加载计划数据')
    loadReadingPlans()
  }
})

onUnload(() => {
  // 页面卸载时移除事件监听
  uni.$off('planChanged')
})
</script>

<style lang="scss" scoped>
// 导入公共样式变量
@import '@/styles/variables.scss';

.home-container {
  padding: 15px;
  background: linear-gradient(135deg, #e0f6ff 0%, #f0fff0 50%, #fff5ee 100%);
  min-height: 100vh;
}

/* 横幅区域 - 自适应高度 */
.banner-container {
  margin-bottom: 16px;
  height: auto;
  width: auto;
}

.banner-swiper {
  height: 60px;
  width: 100%;
  border-radius: 12px;
  overflow: hidden;
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.08);
}

.banner-item {
  position: relative;
  height: 100%;
}

.banner-content {
  position: relative;
  width: 100%;
  height: 100%;
}

/* 暂时不使用的图片相关样式 */
/* .banner-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.banner-overlay {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  background: linear-gradient(transparent, rgba(0, 0, 0, 0.7));
  padding: 20px;
  color: white;
} */

/* 纯文字横幅样式 - 固定高度版 */
.banner-text-only {
  position: relative;
  display: flex;
  align-items: center;
  width: 100%;
  height: 100%;
  padding-left: 16px;
  margin-right: 16px;
  background: linear-gradient(135deg, #ff9595 0%, #ffb347 100%);
}

.banner-text-only .banner-text {
  flex: 1;
  font-size: 14px;
  font-weight: 500;
  line-height: 1.4;
  color: #fff;
  text-shadow: 0 1px 2px rgba(0, 0, 0, 0.3);
  word-wrap: break-word;
  word-break: break-all;
  padding-right: 32px;
}

.banner-text-only .banner-close {
  position: absolute;
  right: 25px;
  top: 50%;
  transform: translateY(-50%);
  display: flex;
  align-items: center;
  justify-content: center;
  width: 24px;
  height: 24px;
  background-color: rgba(255, 255, 255, 0.2);
  border-radius: 50%;
  transition: all 0.3s ease;
}

.banner-text-only .banner-close:active {
  background-color: rgba(255, 255, 255, 0.3);
  transform: scale(0.95);
}

.banner-loading,
.banner-error {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 60px;
  background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%);
  border-radius: 12px;
  color: #6c757d;
  font-size: 12px;
  cursor: pointer;
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.08);
}

.banner-loading .loading-text,
.banner-error .error-text {
  margin-left: 8px;
}

.banner-error:hover {
  background: linear-gradient(135deg, #e9ecef 0%, #dee2e6 100%);
}

/* 搜索框 - 儿童友好风格 */
.search-bar {
  position: relative;
  display: flex;
  align-items: center;
  margin-bottom: 20px;

  .catalog-button {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    padding: 6px 12px;
    height: 44px;
    margin-right: 12px;
    background: linear-gradient(135deg, #42bbff 0%, #87ceeb 100%);
    border-radius: 24px;
    box-shadow: 0 4px 12px rgba(66, 187, 255, 0.3);
    transition: all 0.3s ease;

    .button-icon {
      margin-bottom: 2px;
    }

    .button-text {
      font-size: 10px;
      color: #fff;
      font-weight: 500;
      line-height: 1;
    }

    &:active {
      transform: scale(0.95);
      box-shadow: 0 2px 8px rgba(66, 187, 255, 0.4);
    }
  }

  .search-input {
    flex: 1;
    height: 44px;
    width: 100%;
    padding-left: 10px;
    padding-right: 25px;
    background-color: #fff;
    border-radius: 24px;
    font-size: 16px;
    font-family: 'Inter', sans-serif;
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
    border: 2px solid transparent;
    transition: all 0.3s ease;

    &:focus {
      border-color: #42bbff;
      box-shadow: 0 0 0 3px rgba(66, 187, 255, 0.1);
    }
  }

  .search-icon {
    position: absolute;
    top: 6px;
    right: 55px;
    display: flex;
    align-items: center;
    justify-content: center;
    width: 50px;
    height: 44px;
    color: #42bbff;
    transition: all 0.3s ease;

    &:active {
      transform: scale(0.9);
    }
  }

  .audio-button {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    padding: 6px 8px;
    height: 44px;
    margin-left: 12px;
    background: linear-gradient(135deg, #32cd32 0%, #98fb98 100%);
    border-radius: 24px;
    box-shadow: 0 4px 12px rgba(50, 205, 50, 0.3);
    transition: all 0.3s ease;

    .button-icon {
      margin-bottom: 2px;
    }

    .button-text {
      font-size: 10px;
      color: #fff;
      font-weight: 500;
      line-height: 1;
    }

    &:active {
      transform: scale(0.95);
      box-shadow: 0 2px 8px rgba(50, 205, 50, 0.4);
    }
  }


}

/* 功能目录与绘本集展示区 - 儿童友好风格 */
.category-section {
  margin-bottom: $section-margin;
  @include glass-effect;
  border-radius: $border-radius-xl;
  box-shadow: $shadow-lg;

  .category-header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 10px 20px 0px;

    .category-title {
      font-size: 16px;
      font-weight: 600;
      color: $dark-gray;
    }

    .language-switch {
      display: flex;
      align-items: center;
      gap: 4px;
      padding: 6px 12px;
      background: rgba(255, 255, 255, 0.8);
      border-radius: 16px;
      border: 1px solid rgba(102, 102, 102, 0.2);
      transition: all 0.3s ease;

      .switch-text {
        font-size: 12px;
        color: #666;
        font-weight: 500;
      }

      &:active {
        transform: scale(0.95);
        background: rgba(255, 255, 255, 0.9);
      }
    }
  }

  .category-tabs {
    display: flex;
    justify-content: space-around;
    padding: $spacing-xl 0;
  }

  .category-item {
    display: flex;
    flex-direction: column;
    align-items: center;
    font-size: $font-size-sm;
    color: $dark-gray;
    cursor: pointer;
    transition: $transition-all;

    &.active {
      color: $primary-blue;

      .category-icon-wrapper {
        background: $blue-gradient;
        transform: scale(1.1);
        box-shadow: $shadow-blue;
      }
    }

    &:active {
      transform: scale(0.95);
    }

    .category-icon-wrapper {
      @include center-flex;
      width: $category-icon-size;
      height: $category-icon-size;
      margin-bottom: $spacing-sm;
      background: $medium-gray;
      border-radius: $border-radius-full;
      transition: $transition-all;
      box-shadow: $medium-gray;

      .iconfont {
        color: $white;
        font-size: $icon-lg;
      }

      .icon-text {
        color: $white;
        font-size: $font-size-xl;
        font-weight: $font-weight-semibold;
      }

      .custom-icon {
        width: $icon-lg;
        height: $icon-lg;
        background: $white;
      }
    }
  }
}





/* 阅读计划区块样式 - 儿童友好风格 */
.plan-section {
  // padding: 20px;
  margin-bottom: 20px;
  background: rgba(255, 255, 255, 0.9);
  border-radius: 20px;
  backdrop-filter: blur(10px);
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.08);

  .section-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 20px;
    // margin-bottom: 20px;
    .section-title {
      font-size: 22px;
      font-weight: 600;
      color: #1e293b;
      font-family: 'Inter', sans-serif;
    }
    .section-more {
      font-size: 16px;
      color: #42bbff;
      font-weight: 500;
      padding: 8px 16px;
      background: rgba(66, 187, 255, 0.1);
      border-radius: 20px;
      transition: all 0.3s ease;

      &:active {
        transform: scale(0.95);
        background: rgba(66, 187, 255, 0.2);
      }
    }
  }

  .plan-loading {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    padding: 40px 20px;

    .loading-text {
      margin-top: 10px;
      font-size: 14px;
      color: #666;
    }
  }

  .plan-empty {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    padding: 40px 20px;

    .empty-text {
      margin-top: 16px;
      font-size: 16px;
      font-weight: 500;
      color: #666;
    }

    .empty-desc {
      margin-top: 8px;
      font-size: 14px;
      color: #999;
      text-align: center;
      line-height: 1.4;
    }
  }

  .plan-swiper {
    height: 180px;
    padding: 0px 8px 20px 8px;

    .plan-card {
      padding: 20px 10px;
      background: linear-gradient(135deg, #42bbff 0%, #87ceeb 100%);
      border-radius: 20px;
      margin: 0px 8px;
      box-shadow:
        0 4px 12px rgba(66, 187, 255, 0.2),
        0 2px 6px rgba(0, 0, 0, 0.08),
        inset 0 1px 0 rgba(255, 255, 255, 0.15);
      border: 1px solid rgba(255, 255, 255, 0.15);
      transition: all 0.3s ease;

      &:active {
        transform: translateY(-2px);
        box-shadow:
          0 6px 16px rgba(66, 187, 255, 0.25),
          0 3px 8px rgba(0, 0, 0, 0.1),
          inset 0 1px 0 rgba(255, 255, 255, 0.2);
      }

      .plan-content {
        display: flex;
        align-items: center;
        height: 100%;

        .plan-cover-section {
          display: flex;
          flex-direction: column;
          align-items: center;
          margin-right: 20px;

          .plan-cover {
            width: 88px;
            height: 120px;
            border-radius: 12px;
            margin-bottom: 8px;
            box-shadow: 0 4px 16px rgba(0, 0, 0, 0.2);
            border: 3px solid rgba(255, 255, 255, 0.3);
          }
        }

        .plan-info {
          flex: 1;

          .plan-title-row {
            display: flex;
            align-items: center;
            justify-content: space-between;
            margin-bottom: 16px;

            .plan-name {
              display: block;
              font-size: 18px;
              font-weight: 600;
              color: #fff;
              line-height: 1.4;
              font-family: 'Inter', sans-serif;
              flex: 1;
            }

            .plan-status {
              padding: 4px 8px;
              border-radius: 12px;
              font-size: 12px;
              margin-left: 8px;

              .status-text {
                font-weight: 500;
              }

              &.status-active {
                background-color: rgba(255, 255, 255, 0.2);

                .status-text {
                  color: #fff;
                }
              }

              &.status-paused {
                background-color: rgba(255, 193, 7, 0.2);

                .status-text {
                  color: #ffc107;
                }
              }

              &.status-completed {
                background-color: rgba(40, 167, 69, 0.2);

                .status-text {
                  color: #28a745;
                }
              }

              &.status-cancelled {
                background-color: rgba(220, 53, 69, 0.2);

                .status-text {
                  color: #dc3545;
                }
              }
            }
          }

          .plan-progress {
            display: flex;
            align-items: center;
            margin-bottom: 12px;

            .progress-bar {
              flex: 1;
              height: 10px;
              background-color: rgba(255, 255, 255, 0.3);
              border-radius: 5px;
              margin-right: 16px;
              overflow: hidden;
              position: relative;

              .progress-fill {
                height: 100%;
                background: linear-gradient(90deg, #ffd700 0%, #fff 100%);
                border-radius: 5px;
                transition: width 0.5s ease;
                position: relative;
              }
            }

            .progress-text {
              font-size: 14px;
              color: rgba(255, 255, 255, 0.95);
              min-width: 70px;
              font-weight: 600;
            }
          }
          .plan-days {
            display: flex;

            .current-day {
              font-size: 16px;
              font-weight: 700;
              color: rgba(255, 255, 255, 0.9);
              margin-bottom: 2px;
            }

            .total-days {
              font-size: 16px;
              font-weight: 600;
              color: rgba(255, 255, 255, 0.9);
              margin-bottom: 2px;
            }
          }
        }
      }
    }
  }
}

@keyframes sparkle {
  0%, 100% { transform: translateY(-50%) scale(1); opacity: 1; }
  50% { transform: translateY(-50%) scale(1.2); opacity: 0.8; }
}

/* 图书区块公共样式 - 儿童友好风格 */
.book-section {
  padding: 20px;
  margin-bottom: 20px;
  background: rgba(255, 255, 255, 0.9);
  border-radius: 20px;
  backdrop-filter: blur(10px);
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.08);

  .section-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
    .section-title {
      font-size: 22px;
      font-weight: 600;
      color: #1e293b;
      font-family: 'Inter', sans-serif;
    }
    .section-more {
      font-size: 14px;
      color: #42bbff;
      font-weight: 500;
      padding: 6px 12px;
      background: rgba(66, 187, 255, 0.1);
      border-radius: 16px;
      transition: all 0.3s ease;

      &:active {
        transform: scale(0.95);
        background: rgba(66, 187, 255, 0.2);
      }
    }
    .section-actions {
      display: flex;
      align-items: center;
      gap: 12px;
    }
    .clear-button {
      display: flex;
      align-items: center;
      justify-content: center;
      width: 36px;
      height: 36px;
      border-radius: 50%;
      background: linear-gradient(135deg, #ff9595 0%, #ffb347 100%);
      cursor: pointer;
      transition: all 0.3s ease;
      box-shadow: 0 4px 12px rgba(255, 149, 149, 0.3);

      &:active {
        transform: scale(0.9);
        box-shadow: 0 2px 8px rgba(255, 149, 149, 0.4);
      }
    }
  }
}

/* 横向滚动绘本列表 */
.book-scroll-view {
  white-space: nowrap;
  .book-card-item {
    display: inline-block;
    width: 100px;
    margin-right: 15px;
    cursor: pointer;
    transition: transform 0.2s ease;

    &:active {
      transform: scale(0.95);
    }

    .book-cover {
      width: 100px;
      height: 140px;
      border-radius: 6px;
      background-color: #eee;
      box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
    }
    .book-title-small {
      display: block;
      margin-top: 8px;
      font-size: 14px;
      color: #333;
      white-space: nowrap;
      overflow: hidden;
      text-overflow: ellipsis;
      font-weight: 500;
    }
    .book-progress, .book-source-small {
      display: block;
      font-size: 12px;
      color: #999;
      margin-top: 2px;
    }
  }
}

/* 绘本集网格 - 儿童友好风格 */
.book-grid {
  display: flex;
  flex-wrap: wrap;
  justify-content: left;
  gap: $spacing-md;

  .book-grid-item {
    width: 30%; // 每行显示3个，与中文书架保持一致
    margin-bottom: $spacing-xl;
    display: flex;
    flex-direction: column;
    cursor: pointer;
    transition: $transition-all;

    &:active {
      transform: scale(0.95);
    }

    &:hover {
      transform: translateY(-4px);
    }

    .book-cover-container {
      position: relative;
      width: 100%;

      .book-cover-grid {
        width: 100%;
        height: $book-cover-height; // 使用统一的绘本封面高度变量
        border-radius: $book-cover-radius;
        background-color: $light-gray;
        box-shadow: $shadow-lg;
        transition: $transition-all;
      }

      .book-count-badge {
        position: absolute;
        top: $spacing-sm;
        right: $spacing-sm;
        background: $yellow-gradient;
        color: $dark-gray;
        font-size: $font-size-xs;
        font-weight: $font-weight-semibold;
        padding: $spacing-xs $spacing-sm;
        border-radius: $border-radius-md;
        min-width: 24px;
        text-align: center;
        box-shadow: $shadow-yellow;
        border: 2px solid $white-80;
      }
    }

    .book-title-grid {
      margin-top: $spacing-sm;
      font-size: $font-size-base;
      color: $dark-gray;
      font-weight: $font-weight-medium;
      font-family: $font-family;
      line-height: $line-height-normal;
      @include text-ellipsis-multiline(2);
      height: 40px; // 预留两行的高度
    }

    .book-source-grid {
      margin-top: $spacing-xs;
      font-size: $font-size-sm;
      color: $medium-gray;
    }
  }
}

/* 目录抽屉样式 - 儿童友好风格 */
.catalog-drawer-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.4);
  backdrop-filter: blur(4px);
  z-index: 1000;
  display: flex;
  justify-content: flex-start;
}

.catalog-drawer {
  width: 320px;
  height: 100%;
  @include glass-effect(0.95);
  display: flex;
  flex-direction: column;
  animation: slideInLeft $transition-normal $ease-out;
  box-shadow: $shadow-2xl;
}

@keyframes slideInLeft {
  from {
    transform: translateX(-100%);
  }
  to {
    transform: translateX(0);
  }
}

.drawer-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: $spacing-2xl $spacing-xl;
  border-bottom: 1px solid $border-color-light;
  background: $blue-gradient;

  .drawer-title {
    font-size: $font-size-lg;
    font-weight: $font-weight-semibold;
    color: $white;
    font-family: $font-family;
  }

  .drawer-close {
    @include center-flex;
    width: 32px;
    height: 32px;
    border-radius: $border-radius-full;
    background-color: $white-20;
    cursor: pointer;
    transition: $transition-all;

    &:active {
      background-color: $white-30;
      transform: scale(0.95);
    }
  }
}

.drawer-content {
  flex: 1;
  padding: $spacing-md 0;
}

.drawer-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: $spacing-lg $spacing-2xl;
  cursor: pointer;
  transition: $transition-all;
  border-radius: $border-radius-lg;
  margin: 0 $spacing-md;

  &:active {
    background-color: $light-gray;
    transform: scale(0.98);
  }

  &.active {
    background: rgba(66, 187, 255, 0.1);
    border: 1px solid rgba(66, 187, 255, 0.2);

    .drawer-item-icon .iconfont {
      color: $primary-blue;
    }

    .drawer-item-text {
      color: $primary-blue;
      font-weight: $font-weight-semibold;
    }
  }

  .drawer-item-content {
    display: flex;
    align-items: center;
    gap: $spacing-md;
  }

  .drawer-item-icon {
    @include center-flex;
    width: 24px;
    height: 24px;

    .iconfont {
      font-size: 18px;
      color: $medium-gray;
    }
  }

  .drawer-item-text {
    font-size: $font-size-md;
    color: $dark-gray;
    font-family: $font-family;
  }

  .drawer-item-check {
    @include center-flex;
    color: $primary-blue;
  }
}

/* 加载状态和空状态样式 */
.loading-container {
  @include center-flex;
  flex-direction: column;
  padding: $spacing-2xl;
  gap: $spacing-md;

  .loading-text {
    font-size: $font-size-base;
    color: $medium-gray;
    font-family: $font-family;
  }
}

.empty-container {
  @include center-flex;
  padding: $spacing-2xl;

  .empty-text {
    font-size: $font-size-base;
    color: $medium-gray;
    font-family: $font-family;
  }
}
</style>
